package com.crawler.search.index.service.impl;

import com.crawler.search.index.entity.QueryParam;
import com.crawler.search.index.querier.MultiMatchQuerier;
import com.crawler.search.index.querier.PhraseQuerier;
import com.crawler.search.index.service.ESSearch;
import com.crawler.search.utils.QueryParseUtil;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.rescore.RescorePhase;
import org.elasticsearch.search.rescore.RescorerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 *
 * ES查询
 * @Class Name ESSaverImpl
 * @author zhangyonghui
 * @Create In 下午3:50:26
 */
@Service("esSearch")
public class ESSearchImpl implements ESSearch {

    private static Logger logger = LoggerFactory.getLogger(ESSearchImpl.class);

    @Autowired
	private QueryParseUtil queryParseUtil;

	/**
	 * 多字段match查询
	 * @param
	 * @return
	 */
	@Override
	public String simpleQuery(QueryParam param) {
		String result="{}";
		try {
			//组装查询query
			QueryBuilder multiQuery = new MultiMatchQuerier(param).buildBoolQuery();
			param.setQuery(multiQuery);

			//组装重打分
			QueryBuilder rescoreQuery=new PhraseQuerier(param).buildBoolQuery();
			param.setRescoreQuery(rescoreQuery);

			//查询结果处理
			result = queryParseUtil.getSearchResult(param);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
		}
		return result;
	}



	/**
	 * 多字段match高级查询
	 * @param
	 * @return
	 */
	@Override
	public String seniorQuery(QueryParam param) {
		String result="{}";
		try {
			//组装查询query
			QueryBuilder multiQuery = new MultiMatchQuerier(param).buildSeniorBoolQuery();
			param.setQuery(multiQuery);

			//组装重打分
			QueryBuilder rescoreQuery=new PhraseQuerier(param).buildSeniorBoolQuery();
			param.setRescoreQuery(rescoreQuery);

			//查询结果处理
			result = queryParseUtil.getSearchResult(param);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
		}
		return result;
	}


}
